package com.geek.novel.fragment

import android.annotation.SuppressLint
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.TextView
import com.geek.novel.R
import com.geek.novel.activity.book.BookCategoryActivity
import com.geek.novel.bo.AppContext
import com.geek.novel.common.Constant
import com.geek.novel.entity.BookCategory
import com.geek.novel.network.RslHandler
import com.geek.novel.services.NovelService
import com.geek.novel.ui.BookImageView
import com.geek.novel.vo.ApiErrorResult
import com.geek.novel.vo.ApiResult
import com.geek.novel.vo.BookCategoriesVo
import kotlinx.android.synthetic.main.fragment_book_category.*
import kotlinx.android.synthetic.main.fragment_book_category.classicsHeader
import kotlinx.android.synthetic.main.fragment_book_category.refreshLayout

/**
 * 小说分类页面
 */
class FragmentBookCategory : BaseFragment(), RslHandler {
	
	override fun layoutId(): Int = R.layout.fragment_book_category
	override fun pageName(): String = AppContext.getContext().getString(R.string.title_bar_book_category)
	override fun fragmentName(): String = FragmentName

	/**小说服务*/
	private lateinit var novelService: NovelService

	/**分类列表*/
	private val categoryList = ArrayList<BookCategory>()

	/**适配器对象*/
	private lateinit var  categoryAdapter: BookCategoryGridViewAdapter

	override fun initV() {
		//初始化列表组件
		this.initGridView()

		//初始化下拉刷新功能
		this.initRefreshLayout()

		//初始化服务对象
		novelService = NovelService(this)

		//获取小说分类
		novelService.bookCategories()
	}
	
	override fun myClick(v: View) {
	}


	/**初始化列表组件*/
	private fun initGridView(){
		//初始化适配器
		categoryAdapter = BookCategoryGridViewAdapter(requireContext(), categoryList)
		//添加到布局中
		layout_grid_book_category.adapter = categoryAdapter
		layout_grid_book_category.setOnItemClickListener { _, _, position, _ ->
			val bookCategory = categoryList[position]
			//跳转到分类页面
			val params = Bundle()
			params.putString("category", bookCategory.category)
			params.putString("categoryStr", bookCategory.categoryStr)
			startActivityByAnim(requireContext(), BookCategoryActivity::class.java, params)
		}
	}


	/**
	 * 初始化下拉刷新功能
	 */
	private fun initRefreshLayout(){
		refreshLayout.setRefreshHeader(classicsHeader)
		refreshLayout.setEnableLoadMore(false)//不开启滚动加载
		refreshLayout.setOnRefreshListener { _ ->
			//获取小说分类
			novelService.bookCategories()
		}
	}

	/**适配器*/
	private class BookCategoryGridViewAdapter(private val context: Context, private val list: List<BookCategory>): BaseAdapter(){
		override fun getCount(): Int {
			return list.size
		}
		override fun getItem(position: Int): Any {
			return position
		}
		override fun getItemId(position: Int): Long {
			return position.toLong()
		}
		@SuppressLint("ViewHolder", "InflateParams", "SetTextI18n")
		override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
			val bookCategory = list[position]
			val view = LayoutInflater.from(context).inflate(R.layout.grid_view_book_category, null)//用parent会报错，神奇
			//图片
			val imageView = view.findViewById<BookImageView>(R.id.iv_book_category_image)
			val imgId = bookCategory.imgId
			imageView.setBookName(bookCategory.bookName)
			imageView.loadBookImage(imgId)

			//分类名称
			val bookCategoryStr = view.findViewById<TextView>(R.id.tv_book_category_str)
			bookCategoryStr.text = bookCategory.categoryStr
			//分类的书籍数量
			val bookCategoryCount = view.findViewById<TextView>(R.id.tv_book_category_count)
			bookCategoryCount.text = "共${bookCategory.count}册"
			return view
		}

	}

	
	companion object {
		const val FragmentName = "FragmentBookCategory"
		/**单例instance*/
		@SuppressLint("StaticFieldLeak")
		private var instance: FragmentBookCategory? = null
		fun newInstance(): FragmentBookCategory{
			if(instance == null){
				instance = FragmentBookCategory()
			}
			return instance!!
		}
	}

	override fun onError(code: Int, err: ApiErrorResult) {
		when(code){
			//获取小说分类
			Constant.HTTP_KEY_APP_GET_BOOK_CATEGORIES->{
				//更新滚动加载的状态
				refreshLayout.finishRefresh(false)
			}
		}
	}

	override fun onSuccess(result: ApiResult, code: Int) {
		when(code){
			//获取小说分类
			Constant.HTTP_KEY_APP_GET_BOOK_CATEGORIES->{
				//更新滚动加载的状态
				refreshLayout.finishRefresh(true)
				//获取分类数据
				val vo = result.getData() as BookCategoriesVo
				categoryList.clear()
				categoryList.addAll(vo.categories!!)
				categoryAdapter.notifyDataSetChanged()
			}
		}
	}

}
